package com.woniuxy.oa.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.woniuxy.oa.entity.Attendance;
import com.woniuxy.oa.entity.Employee;
import com.woniuxy.oa.entity.PageBean;
import com.woniuxy.oa.service.AttendanceService;
import com.woniuxy.oa.utils.CurrentDateUtils;
import com.woniuxy.oa.utils.TimeAddAnotherTime;

@Controller
//配置命名空间
@RequestMapping("/Attendance")
public class AttendanceController {
	
	@Autowired
	AttendanceService attendanceService;

	public void setAttendanceService(AttendanceService attendanceService) {
		this.attendanceService = attendanceService;
	}
	
	//签到
	@ResponseBody
	@RequestMapping("/signIn")
	public int SignIn(HttpServletRequest request,HttpServletResponse response) {
		System.out.println("执行签到方法");
		//获取当前操作用户(从域中取出)
//		Employee emp = (Employee) request.getSession().getAttribute("user");
//		Integer userid = emp.getId();
//		String username = emp.getUsername();
		
		Attendance attendance = new Attendance();
		//获取到当前考勤日期
		String am_date = CurrentDateUtils.getCurrentDate();
		//获取当前时间
		String am_signtime = CurrentDateUtils.getCurrenttime();
		//这里先暂时自定义用户id和用户名
		attendance.setAm_userid(1);
		attendance.setAm_username("小明");
		attendance.setAm_date(am_date);
		attendance.setAm_signtime(am_signtime);
		attendance.setAm_userip("192.168.0.1");
		//签到控制
		int result = 0;//签到失败
		try {
			//打卡范围，签到时间inTtime范围从域中取出
			String as_worktime = (String) request.getSession().getAttribute("as_worktime");
			System.out.println("签到设定时间为："+as_worktime);
			Date inTime = CurrentDateUtils.stringToDate(as_worktime);
			//超过上班时间30min内，签到成功，但为迟到状态
			String outtime = TimeAddAnotherTime.TimeAdd(as_worktime, "30");
			System.out.println("添加30min时间为："+outtime);
			Date outTime = CurrentDateUtils.stringToDate(outtime);
			Date nowTime = CurrentDateUtils.stringToDate(am_signtime);
			//判断当前是否已经签到
			//从数据库查看是否有签到的记录(根据用户id和签到日期am_date查询)
			String isSignIn = attendanceService.selectIsSignIn(attendance);
			if(isSignIn == null) {
				if(nowTime.before(outTime)&&nowTime.after(inTime)) {
					System.out.println("迟到");
					//迟到
					attendanceService.insertSignIn(attendance);
					result = -2;
				}else if(nowTime.after(outTime)) {
					System.out.println("缺勤");
					//缺勤
					result = -3;
				}else if(nowTime.before(inTime)) {
					System.out.println("签到成功");
					//未签到
					result = attendanceService.insertSignIn(attendance);
					return result;
				}
			}else {
				System.out.println("已经签到");
				//已经签到
				return 2;
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", e.getMessage());
			
		}
		return result;
	}
	
	//签退
	@ResponseBody
	@RequestMapping("/signBack")
	public int signBack(HttpServletRequest request,HttpServletResponse response) {
		System.out.println("执行签退方法");
		//获取当前操作用户(从域中取出)
//		User user = (User) request.getSession().getAttribute("user");
//		int userid = user.getId();
		
		//获取请求参数
		Attendance attendance = new Attendance();
		
		String am_signbacktime = CurrentDateUtils.getCurrenttime();
		attendance.setAm_signbacktime(am_signbacktime);
		attendance.setAm_userid(1);
		attendance.setAm_date(CurrentDateUtils.getCurrentDate());
		//定义一个时间（考勤设置里面的下班时间），在这个时间之前不能签退
		String as_getofftime = (String) request.getSession().getAttribute("as_getofftime");
		System.out.println("签退时间为："+as_getofftime);
		Date inTime = CurrentDateUtils.stringToDate(as_getofftime);
//		System.out.println(inTime);
		Date nowTime = CurrentDateUtils.stringToDate(am_signbacktime);
//		System.out.println(nowTime);
		
		//查看当前是否已经签到,签到成功后才可以签退
		String isSignIn = attendanceService.selectIsSignIn(attendance);
		//判断当前是否已经签到，避免用户重复签退
		String isSignBack = attendanceService.selectIsSignBack(attendance);
		int result = 0;//表示签退到失败
		try {
			if(isSignIn!=null) {
				//签到成功，判断当前用户是否已经签退
				if(isSignBack==null) {
					//说明没有签退
					if(nowTime.before(inTime)) {
						//在17:30之前不能签退
						return -3;
					}else {
						//签退成功
						result = attendanceService.updateSignBack(attendance); 
						return result;
					} 
				}
			}else {
				//提示，还没有签到请先签到
				return -2;
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", e.getMessage());
		}
		return result;
	}
	
	//签到成功和签退成功都跳转页面展示考勤信息
	@ResponseBody
	@RequestMapping("/showAttendance")
	public Attendance showInfo(HttpServletRequest request,HttpServletResponse response) {
		//获取当前操作用户(从域中取出)
//		User user = (User) request.getSession().getAttribute("user");
//		int userid = user.getId();
		System.out.println("正在执行查询操作");
		Attendance attendance = new Attendance();
		try {
			//获取当前考勤日期
			String am_date = CurrentDateUtils.getCurrentDate();
			int userid = 1;
			attendance.setAm_userid(userid);
			attendance.setAm_date(am_date);
			attendance = attendanceService.selectAllAttendanceByDateAndUserid(attendance);
			return attendance;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", e.getMessage());
		}
		return attendance;
	}
	
	/**
	 * 根据考勤日期分页展示数据
	 */
	
	//从页面上获取url路径参数
	public String getUrl(HttpServletRequest request) {
		//获取url中的工程名
		String contextPath = request.getContextPath();
		//获取url中的controller映射名
		String servletPath = request.getServletPath();
		//获取url中的参数
		String queryString = request.getQueryString();
		//获取到的url参数中不包括pageIndex数据，因为这个数据使我们通过点击页面上的链接得到的，因此需要去掉这个数据
		if(queryString!=null && queryString.indexOf("&pageIndex=")!=-1) {
			//包含pageIndex数据，就截取该参数
			queryString = queryString.substring(0, queryString.indexOf("&pageIndex="));
		}
		System.out.println("getUrl----"+(contextPath+servletPath+"?"+queryString));
		return contextPath+servletPath+"?"+queryString;
	}
	
	//获取用户传参,封装为一个方法
	private int getPageIndex(HttpServletRequest request) {
		if(request.getParameter("pageIndex")==null || request.getParameter("pageIndex").equals("")) {
			//说明用户没有传参，我们默认传入1
			return 1;
		}
		//用户传参
		return Integer.parseInt(request.getParameter("pageIndex"));
	}
	
	//根据考勤日期查询考勤信息，并做分页展示
	@ResponseBody
	@RequestMapping("/showAttendancesByPage")
	public PageBean<Attendance> getAttendancesByPage(HttpServletRequest request){
		
		PageBean<Attendance> pageBean = null;
		try {
			//获取页面参数，也可以直接传参
			String startDate = request.getParameter("startDate");
			String endDate = request.getParameter("endDate");
			//获取用户传入的当前页
			int pageIndex = getPageIndex(request);
			int pageSize = 10;
			pageBean = attendanceService.getAttendanceConditionByPage(
					pageIndex,pageSize, startDate,endDate);
			pageBean.setUrl(getUrl(request));
			return pageBean;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", e.getMessage());
			return pageBean;
		}
	}
	
}
